package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public UserVo login(LoginDto loginDto) {

        //根据用户名查询用户
        User user = userMapper.selectByUsername(loginDto.getUsername());
        //判断用户是否存在
        if(ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        //判断用户是否被禁用
        if(user.getDataState().equals(SuperConstant.DATA_STATE_1)){
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }

        //密码是否正确
        if(!BCrypt.checkpw(loginDto.getPassword(),user.getPassword())){
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }

        //对象的转换
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);

        //密码脱敏
        userVo.setPassword("");

        //获取用户的资源列表数据
        List<String> urlList = resourceMapper.selectListByUserId(user.getId());
        //获取白名单数据
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        //合并
        urlList.addAll(publicAccessUrls);

        //生成jwt的token
        Map<String,Object> climas = new HashMap<>();
        climas.put("currentUser", JSONUtil.toJsonStr(userVo));

        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), climas);
        userVo.setUserToken(token);

        //存储数据到redis中
        String key = CacheConstants.PUBLIC_ACCESS_URLS+user.getId();
        int ttl = jwtTokenManagerProperties.getTtl() / 1000;
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(urlList),ttl, TimeUnit.SECONDS);

        return userVo;
    }
}
